package com.hanson.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSONObject;
import com.hanson.Const;
import com.hanson.api_bean.GoodsDetail;
import com.hanson.common.bean.HaiBaiBean;
import com.hanson.common.bean.ResultMessage;
import com.hanson.common.bean.WeiXinConfig;
import com.hanson.common.exception.BusinessException;
import com.hanson.common.util.BusinessUtil;
import com.hanson.common.util.FileUploadUtil;
import com.hanson.common.util.ImageUtil;
import com.hanson.common.util.WeiXinShareUtil;
import com.hanson.entity.GoodsBean;
import com.hanson.entity.GroupGoodsBean;
import com.hanson.entity.SeckillGoodsBean;
import com.hanson.entity.UserBean;
import com.hanson.service.*;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.enums.TicketType;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Api(tags = "商品数据管理")
@RestController
@RequestMapping("/api/goods")
public class GoodsApiController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CartService cartService;
    @Autowired
    private UserService userService;
    @Autowired
    private GoodsCommentService goodsCommentService;
    @Autowired
    private GoodsCollectService goodsCollectService;
    @Autowired
    private UserShareService userShareService;
    @Autowired
    private GoodsScoreService goodsScoreService;
    @Autowired
    private GroupGoodsService groupGoodsService;
    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private WeiXinConfig weiXinConfig;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private WxMpService wxMpService;
    @Value("${share.path}")
    private String sharePath;
    @Value("${oss.local}")
    private String isLocal;

    @ApiOperation(value = "获取商品详情数据")
    @RequestMapping(value = "/goodsDetail/{id}", method = RequestMethod.GET)
    public ResultMessage goodsDetail(@PathVariable String id, @RequestParam(defaultValue = "0") String parentId, HttpServletRequest request) throws Exception {
        if (!StringUtils.isNumeric(id)) {
            log.error("商品已下架 id:{}", id);
            throw new BusinessException("商品已下架");
        }
        GoodsBean goodsBean = goodsService.detail(Integer.parseInt(id));
        if (null == goodsBean) {
            log.error("商品已下架 id:{}", id);
            throw new BusinessException("商品已下架");
        }
        GoodsDetail goodsDetail = new GoodsDetail();
        goodsDetail.setGoodsBean(goodsBean);
        if (null != goodsBean.getIsScore() && goodsBean.getIsScore() == 1) {
            //积分兑换商品
            goodsDetail.setGoodsScoreBean(goodsScoreService.getGoodsScore(goodsBean.getId()));
        }
        String openId = BusinessUtil.getHeaderOpenId(request);
        if (StringUtils.isNotEmpty(openId)) {
            goodsDetail.setCartCount(cartService.countByOpenId(openId));
            goodsDetail.setIsCollect(goodsCollectService.count(openId, Integer.parseInt(id)));
            UserBean userBean = userService.selectByOpenId(openId);
            if (null == userBean) {
                goodsDetail.setIsVip(0);
            } else {
                goodsDetail.setIsVip(userBean.getIsVip());
            }
        }
        ModelMap modelMap = new ModelMap();
        goodsDetail.setComments(goodsCommentService.selectByGoodsId(Integer.parseInt(id), 0, modelMap));
        goodsDetail.setCommentsStatis(modelMap);
        return ResultMessage.success(goodsDetail, null);
    }

    /**
     * 获取商品分享链接
     *
     * @param client
     * @param goodsType
     * @return
     */
    private String getShareUrl(String client, Integer goodsType) {
        if (client.equalsIgnoreCase(Const.CLIENT_MINI)) {
            if (goodsType == 1) {
                return "index/goodsDetail/goodsDetail";
            } else if (goodsType == 2) {
                return "index/groupDetail/groupDetail";
            } else if (goodsType == 3) {
                return "index/skillDetail/skillDetail";
            } else if (goodsType == 4) {
                return "index/integralDetail/integralDetail";
            } else {
                throw new BusinessException("goodsType不正确");
            }
        } else {
            if (goodsType == 1) {
                return "%s#/index/goodsDetail/goodsDetail?id=%s&uid=%s";
            } else if (goodsType == 2) {
                return "%s#/index/groupDetail/groupDetail?id=%s&uid=%s";
            } else if (goodsType == 3) {
                return "%s#/index/skillDetail/skillDetail?id=%s&uid=%s";
            } else if (goodsType == 4) {
                return "%s#/index/integralDetail/integralDetail?id=%s&uid=%s";
            } else {
                throw new BusinessException("goodsType不正确");
            }
        }
    }

    @ApiOperation(value = "获取海报分享数据", notes = "goodsType 1:普通商品 2：拼团商品 3：秒杀商品 4:积分兑换")
    @RequestMapping(value = "/getShareImgs/{goodsId}/{goodsType}", method = RequestMethod.GET)
    public ResultMessage add(@PathVariable String goodsId, @PathVariable Integer goodsType, HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        String client = BusinessUtil.getHeaderClient(request);
        int clientType = client.equalsIgnoreCase(Const.CLIENT_MINI) ? 1 : 2;
        List<String> returnList = userShareService.getShareImgs(openId, goodsId, clientType, goodsType);
        if (CollectionUtils.isEmpty(returnList)) {
            HaiBaiBean haiBaiBean = new HaiBaiBean();
            GoodsBean goodsBean = null;
            if (goodsType == 1 || goodsType == 4) {
                goodsBean = goodsService.selectById(goodsId);
            } else if (goodsType == 2) {
                GroupGoodsBean groupGoodsBean = groupGoodsService.selectById(Integer.parseInt(goodsId));
                if (null != groupGoodsBean) {
                    goodsBean = goodsService.selectById(groupGoodsBean.getGoodsId() + "");
                }
            } else if (goodsType == 3) {
                SeckillGoodsBean seckillGoodsBean = seckillGoodsService.selectById(Integer.parseInt(goodsId));
                if (null != seckillGoodsBean) {
                    goodsBean = goodsService.selectById(seckillGoodsBean.getGoodsId() + "");
                }
            }

            if (null == goodsBean) {
                log.error("商品分享找到商品信息 goodsId:{} goodsType:{}", goodsId, goodsType);
                goodsBean = new GoodsBean();
            }
            if (null != goodsBean) {
                haiBaiBean.setGoodsId(goodsId);
                haiBaiBean.setGoodsName(goodsBean.getGoodsName());
                haiBaiBean.setGoodsImage(goodsBean.getImage());
                haiBaiBean.setPrice(BusinessUtil.getWebAmount(goodsBean.getPrice()));
                haiBaiBean.setVipPrice(BusinessUtil.getWebAmount(goodsBean.getVipPrice()));
            }
            UserBean userBean = userService.selectByOpenId(openId);
            if (null != userBean) {
                haiBaiBean.setUserName(userBean.getNickName());
                haiBaiBean.setUserImage(userBean.getHeadImg());
            }
            String templateUrl = getShareUrl(client, goodsType);
            if (client.equalsIgnoreCase(Const.CLIENT_MINI)) {
                try {
                    String scene = "id=%s&uid=%s";
                    byte[] imagesBytes = wxMaService.getQrcodeService().createWxaCodeUnlimitBytes(String.format(scene, goodsId, userBean.getId()),
                            templateUrl,
                            300, true, null, false);
                    BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imagesBytes));
                    haiBaiBean.setQrImage(bufferedImage);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("获取小程序二维码失败", e.getMessage());
                }
            } else {
                BufferedImage bufferedImage = BusinessUtil.generateQRCode(String.format(templateUrl, weiXinConfig.getDomian(), goodsId, userBean.getId()), 300, 300);
                haiBaiBean.setQrImage(bufferedImage);
            }
            returnList = new ArrayList();
            returnList.add(imageToUrl(ImageUtil.createImg1(haiBaiBean)));
            returnList.add(imageToUrl(ImageUtil.createImg2(haiBaiBean)));
            returnList.add(imageToUrl(ImageUtil.createImg3(haiBaiBean)));
            userShareService.batchInsert(openId, goodsId, clientType, goodsType, returnList);
        }

        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setData(returnList);
        resultMessage.setMsg("获取分享海报成功！");
        return resultMessage;
    }

    public static void main(String[] args) throws IOException {
        HaiBaiBean haiBaiBean = new HaiBaiBean();
        haiBaiBean.setGoodsId(1+"");
        haiBaiBean.setGoodsName("商品商品商品");
        haiBaiBean.setGoodsImage("http://kaobaobaotest.oss-cn-qingdao.aliyuncs.com/5.png");
        haiBaiBean.setPrice(BusinessUtil.getWebAmount(100));
        haiBaiBean.setVipPrice(BusinessUtil.getWebAmount(100));
        haiBaiBean.setUserName("廖华强");
        haiBaiBean.setUserImage("http://kaobaobaotest.oss-cn-qingdao.aliyuncs.com/5.png");
        BufferedImage bufferedImage = ImageUtil.createImg3(haiBaiBean);
        File outputfile = new File("C:\\Users\\24026\\Desktop\\test\\好沐友二期\\image.jpg");

        ImageIO.write(bufferedImage, "jpg", outputfile);
    }

    /**
     * jsonobj中一个参数：url
     *
     * @param jsonObject
     * @return
     * @throws WxErrorException
     */
    @ApiOperation(value = "微信公众号分享参数")
    @RequestMapping(value = "/getShareParam", method = RequestMethod.POST)
    public ResultMessage getShareParam(@RequestBody JSONObject jsonObject) throws WxErrorException {
        ResultMessage resultMessage = new ResultMessage();
        log.info("getShareParam url:{}", jsonObject.getString("url"));
        resultMessage.setData(WeiXinShareUtil.getWxConfig(jsonObject.getString("url"), weiXinConfig.getAppId(), wxMpService.getTicket(TicketType.JSAPI)));
        return resultMessage;
    }

    @ApiOperation(value = "保存分享结果")
    @RequestMapping(value = "/saveShareResult/{goodsId}/{pId}", method = RequestMethod.POST)
    public ResultMessage saveShareResult(@PathVariable Integer goodsId, @PathVariable Integer pId, HttpServletRequest request) {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ResultMessage resultMessage = new ResultMessage();
        userShareService.addShareGoods(goodsId, pId, openId);
        resultMessage.setMsg("保存成功！");
        return resultMessage;
    }

    private String imageToUrl(BufferedImage img) throws Exception {
        String fileName = UUID.randomUUID() + ".jpg";
        FileOutputStream fos = new FileOutputStream(sharePath + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
        encoder.encode(img);
        bos.close();
        fos.close();
        return FileUploadUtil.uploadFileSystem(isLocal, sharePath + fileName);
    }

}
